package com.xxx.shetuan3.config;

import com.google.gson.Gson;
import com.xxx.shetuan3.common.CommonResult;
import com.xxx.shetuan3.common.CommonResultCode;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Component
public class My401 implements AuthenticationEntryPoint {

    @Override
    @ApiOperation("匿名用户无权限，https://www.cnblogs.com/cnsec/p/13407130.html")
    public void commence(HttpServletRequest httpServletRequest, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
        //response.setCharacterEncoding(CommonConstants.UTF8);
        //response.setContentType(CommonConstants.CONTENT_TYPE);
        CommonResult result = CommonResult.failed(CommonResultCode.UNAUTHORIZED) ;

        response.setCharacterEncoding("utf-8");
        response.setContentType("text/javascript;charset=utf-8");
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        PrintWriter printWriter = response.getWriter();
        Gson gson = new Gson();
        String json401 = gson.toJson(result);
        printWriter.append(json401);
    }
}
